package com.Liux.blog.service.impl;

import com.Liux.blog.dao.ArticleTypeMapper;
import com.Liux.blog.entity.ArticleType;
import com.Liux.blog.service.ArticleService;
import com.Liux.blog.service.ArticleTypeService;
import com.Liux.blog.util.PageHelper;
import com.Liux.blog.vo.ResultStatus;
import com.Liux.blog.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.UUID;

@Service
public class ArticleTypeServiceImpl implements ArticleTypeService {

    @Autowired
    private ArticleTypeMapper articleTypeMapper;

    public ResultVo Result(int i,Object data){
        ResultVo resultVo;
        if(i>0){
            resultVo = new ResultVo(ResultStatus.OK,"success",data);
        }else{
            resultVo = new ResultVo(ResultStatus.NO,"fail",null);
        }
        return resultVo;
    }

    @Override
    public ResultVo addType(ArticleType articleType) {
        articleType.setId(UUID.randomUUID().toString());
        int i = articleTypeMapper.insert(articleType);
        return Result(i,articleType);
    }

    @Override
    public ResultVo delType(String id) {
        int i = articleTypeMapper.delArticleType(id);
        return Result(i,null);
    }

    @Override
    public ResultVo updateType(ArticleType articleType) {
        Example example = new Example(ArticleType.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",articleType.getId());
        criteria.andEqualTo("typeName",articleType.getTypeName());
        int i = articleTypeMapper.updateByExample(articleType, example);
        return Result(i,null);
    }

    @Override
    public ResultVo TypeList(int pageNum, int limit) {
        int start = (pageNum-1) * limit;

        List<ArticleType> articleType = articleTypeMapper.getArticleType(start, limit);

        Example example = new Example(ArticleType.class);
        Example.Criteria criteria = example.createCriteria();
        int count = articleTypeMapper.selectCountByExample(example);

        int pageCount = count % limit == 0 ? count/limit : count/limit+1;

        PageHelper<ArticleType> articleTypePageHelper = new PageHelper<>(count, pageCount, articleType);

        return Result(articleTypePageHelper.getCount(),articleTypePageHelper);
    }
}
